package controler;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import dao.GetCnn;
import dao.common;

import model.SanphamModel;
import model.UpfileModel;

/**
 * Servlet implementation class quanlysanpham
 */
@WebServlet("/quanlysanpham")
public class quanlysanpham extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public quanlysanpham() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @throws SQLException 
	 * @throws IOException 
	 * @throws ServletException 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException{
    	response.setContentType("text/html;charset=UTF-8");
    	HttpSession session = request.getSession();
    	common cm = new common();   	
    	if(cm.checkquyen(session)== false){
    		response.sendRedirect("trangchu");
    	}
    	else{
    		String saveFilepath = "" ;
	    	List<String> arr = new ArrayList<String>();
	    	Connection cnn = GetCnn.getCnn();
			Statement stat = cnn.createStatement();
			
			
			
			UpfileModel umodel = new UpfileModel();
			Hashtable params = new Hashtable();
			
			if (!ServletFileUpload.isMultipartContent(request)) {
				// if not, we stop here
				PrintWriter writer = response.getWriter();
				writer.println("Error: Form must has enctype=multipart/form-data.");
				writer.flush();
				return;
			}
			else{
				DiskFileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				List items = null;
				try {
					items =upload.parseRequest(request);
				} catch (FileUploadException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Iterator iter = items.iterator();
				String fileName = null;
				
				while(iter.hasNext()){
					FileItem item = (FileItem)iter.next();
					if(item.isFormField()){
						params.put(item.getFieldName(), item.getString());
					}
					else{
						String itemName = item.getName();
						fileName = itemName.substring(itemName.lastIndexOf("\\")+1);
						String RealPath =getServletContext().getRealPath("/");
						RealPath = umodel.getpath(RealPath) +fileName ;
						saveFilepath = umodel.getfilePath(RealPath);
						arr.add(saveFilepath);
						File saveFile = new File(RealPath);
						try {
							item.write(saveFile);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
	
	
	    	String option = request.getParameter("option");
	    	String tensp =(String) params.get("tensp");
	    	tensp = new String(tensp.getBytes("8859_1"),"UTF8");
	    	String mota = (String) params.get("mota");
	    	mota = new String(mota.getBytes("8859_1"),"UTF8");
	    	String giaban = (String) params.get("giaban");
	    	String discount = (String) params.get("discount");
	    	String thuonghieu =(String)params.get("thuonghieu");
	    	thuonghieu = new String(thuonghieu.getBytes("8859_1"),"UTF8");
	    	String soluong = (String)params.get("soluong");
	    	String urlhinh = "";
	    	String urlhinh2 = "";
	    	String urlhinh3 = "";
	    	if(arr.get(0)!=null){
	    		urlhinh = arr.get(0);
	    	}
	    	if(arr.get(1)!= null){
	    		urlhinh2 = arr.get(1);
	    	}
	    	if(arr.get(2)!= null){
	    		urlhinh3 = arr.get(2);
	    	}
	    	String madanhmuc = (String) params.get("MADANHMUC");
	    	String ma_sp = (String) params.get("masp");
	    	String sSQL ="";
	    	if(option.equals("addnew")){
	    		int masp1 = 0;
	    		SanphamModel model = new SanphamModel();
	    		masp1 = model.getTotalRows("select * from SANPHAM") + 2;
	    		sSQL = "insert into SANPHAM(MASP,MADANHMUC,TENSP,MOTA,GIABAN,NGAYDANG,DISCOUNT,URLHINH,URLHINH2,URLHINH3,THUONGHIEU,SOLUONG) VALUES('"+masp1+"','"+madanhmuc+"',N'"+tensp+"',N'"+mota+"','"+giaban+"',getdate(),'"+discount+"','"+urlhinh+"','"+urlhinh2+"','"+urlhinh3+"',N'"+thuonghieu+"','"+soluong+"')";
	    		stat.executeUpdate(sSQL);
	    	}
	
	    	if(option.equals("edit")){
	    		sSQL = "update SANPHAM set TENSP = N'"+tensp+"',MOTA = N'"+mota+"',GIABAN = '"+giaban+"',DISCOUNT ='"+discount+"',URLHINH = '"+arr.get(0)+"',URLHINH2 = '"+arr.get(1)+"',URLHINH3 = '"+arr.get(2)+"',thuonghieu = N'"+thuonghieu+"',soluong ='"+soluong+"' where MASP = '"+ma_sp+"'";
	    		stat.executeUpdate(sSQL);
	    	}
	    	
	    	response.sendRedirect("admintimsanpham.jsp");
    	}
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			processRequest(request,response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			processRequest(request,response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
